<?php

namespace Api\Controller;

use Common\Controller;
use Common\Utils\sms\Sms;
use Common\Utils\validate\Validate;

class AccountController extends Controller\ApiController {

    private $userModel;
    private $vcodeModel;
    private $areaModel;
    private $categoryModel;
    private $categoryLabelModel;
    private $shopsModel;
    private $userBusinessDistrictModel;
    private $userCategoryModel;
    private $userLikeShopModel;

    public function __construct() {
        $this->userModel = D('User');
        $this->vcodeModel = D('Vcode');
        $this->areaModel = D('Area');
        $this->categoryModel = D('Category');
        $this->categoryLabelModel = D('CategoryLabel');
        $this->shopsModel = D('Shops');
        $this->userBusinessDistrictModel = D('UserBusinessDistrict');
        $this->userCategoryModel = D('UserCategory');
        $this->userLikeShopModel = D('UserLikeShop');
    }

    /**
     * @name 发送注册验证码
     * @param $mobile
     */
    public function sendVcode() {
        //1.接收参数并验证
        $mobile = getParameter('mobile');
        $vcode_type = getParameter('vcode_type');
        $params = array(
            array('key' => 'mobile', 'val' => $mobile, 'require' => true, 'type' => 'mobile', 'msg' => '手机号格式不正确！'),
            array('key' => 'vcode_type', 'val' => $vcode_type, 'require' => true, 'type' => 'range', 'arr' => C('VCODE_TYPE'), 'msg' => '验证码类型不正确！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }

        switch ($vcode_type) {
            case C('VCODE_TYPE.REGISTER'):
                //2.验证用户，是否已经注册
                if ($this->userModel->getInfoByMobile($mobile)) {
                    $this->error('手机号已注册');
                }
                break;
        }

        //3.发送验证码
        $vcode = $this->vcodeModel->addVcode($mobile, $vcode_type);
        if ($vcode == false) {
            $this->error('每1分钟只能发送一次，请勿重复提交。');
        }
        $result = Sms::sendVcode($mobile, $vcode);

        //4.返回结果
        if ($result) {
            $this->success('发送验证码成功，请注意查收短信。');
        } else {
            $this->error('发送失败！');
        }
    }

    /**
     * @name 检测验证码是否正确
     * @param  $mobile
     * @param  $vcode
     */
    public function verifyVcode($mobile = false, $vcode = false, $vcode_type = false) {
        //1.接收参数并验证
        if ($mobile) {
            $isLoad = true;
        } else {
            $isLoad = false;
        }
        $mobile = $mobile == false ? getParameter('mobile') : $mobile;
        $vcode = $vcode == false ? getParameter('vcode') : $vcode;
        $vcode_type = $vcode_type == false ? getParameter('vcode_type') : $vcode_type;


        $params = array(
            array('key' => 'mobile', 'val' => $mobile, 'require' => true, 'type' => 'mobile', 'msg' => '手机号格式不正确！'),
            array('key' => 'vcode', 'val' => $vcode, 'require' => true, 'msg' => '验证码不能为空！'),
            array('key' => 'vcode_type', 'val' => $vcode_type, 'require' => true, 'type' => 'range', 'arr' => C('VCODE_TYPE'), 'msg' => '验证码类型不正确！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }

        //2.检查验证码是否有效及是否正确
        $result = $this->vcodeModel->verifyVcode($mobile, $vcode, $vcode_type);
        switch ($result) {
            case C('VERIFY_VCODE.RIGHT'):
                if ($isLoad == false) {
                    $this->success('验证成功');
                } else {
                    return true;
                }
                break;
            case C('VERIFY_VCODE.INVALID'):
                $this->error('验证码已过期,请重新获取。');
                break;
            case C('VERIFY_VCODE.ERROR'):
                $this->error('验证码错误');
                break;
        }
    }

    /**
     * @name 用户注册
     * @param $mobile
     * @param $password
     */
    public function register() {
        //1.接收参数并验证
        $mobile = getParameter('mobile');
        $password = getParameter('password');
        $nickname = getParameter('nickname');
        $params = array(
            array('key' => 'nickname', 'val' => $nickname, 'require' => true, 'msg' => '昵称不能为空！'),
            array('key' => 'mobile', 'val' => $mobile, 'require' => true, 'type' => 'mobile', 'msg' => ' 手机号格式不正确！'),
            array('key' => 'password', 'val' => $password, 'require' => true, 'min' => 5, 'max' => 10, 'msg' => '密码格式不正确，请填写5-10位密码！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }

        //2.检测手机号是否已被注册
        if ($this->userModel->getInfoByMobile($mobile)) {
            $this->error('手机号已注册');
        }

        //3.提交注册
        if ($this->userModel->register($mobile, $password, $nickname)) {
            //3.1自动登陆
            $userInfo = $this->userModel->getInfoByMobile($mobile);
            $token = $this->userModel->makeToken($userInfo['id'], $mobile);
            $data = array('token' => $token);
            $this->output($data, '注册成功');
        } else {
            $this->error('数据库繁忙，请稍后再试');
        }
    }

    /**
     * @name 登陆
     * @param $mobile
     * @param $password
     */
    public function login() {
        //1.接收参数并验证
        $mobile = getParameter('mobile');
        $password = getParameter('password');
        $params = array(
            array('key' => 'mobile', 'val' => $mobile, 'require' => true, 'type' => 'mobile', 'msg' => '手机号格式不正确！'),
            array('key' => 'password', 'val' => $password, 'require' => true, 'min' => 5, 'max' => 10, 'msg' => '密码格式不正确，请填写5-10位密码！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //2.验证登陆
        $result = $this->userModel->login($mobile, $password);
        switch ($result) {
            case C('LOGIN_STATUS.SUCCESS'):
                $userInfo = $this->userModel->getInfoByMobile($mobile);
                $token = $this->userModel->makeToken($userInfo['id'], $userInfo['mobile']);
                $data = array('token' => $token);
                $this->output($data, '登陆成功');
                break;
            case C('LOGIN_STATUS.PASSWORD_ERROR'):
                $this->error('密码错误!');
                break;
            case C('LOGIN_STATUS.INEXISTENCE'):
                $this->error('账号不存在');
                break;
        }
    }

    /**
     * @name 找回密码
     * @param $mobile
     * @param $password
     * @param $vcode
     */
    public function findPassword() {
        //1.接收参数并验证
        $mobile = getParameter('mobile');
        $password = getParameter('password');
        $vcode = getParameter('vcode');
        $params = array(
            array('key' => 'password', 'val' => $password, 'require' => true, 'min' => 5, 'max' => 10, 'msg' => '密码格式不正确，请填写5-10位密码！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //2.判断验证码是否正确
        $this->verifyVcode($mobile, $vcode, C('VCODE_TYPE.FINDPASSWORD'));
        //3.修改密码
        $result = $this->userModel->rePassword($mobile, $password);
        if ($result) {
            $this->success('密码修改成功！');
        } else {
            $this->error('密码修改失败！');
        }
    }

    /**
     * @name 获取省份列表
     */
    public function getProvince() {
        //1.验证是否登陆
        parent::auth();
        //2.获取省份列表
        $result = $this->areaModel->getProvince();
        $this->output($result);
    }

    /**
     * @name 获取城市列表
     * @param $province_id
     */
    public function getCity() {
        $result = $this->areaModel->getCity();
        $this->output($result);
    }

    /**
     * @name 获取地区列表
     * @param $city_id
     * @param $city_name
     */
    public function getArea() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $cityId = getParameter('city_id');
        $cityName = getParameter('city_name');
        $params = array(
            array('key' => 'city_id', 'val' => $cityId, 'require' => false, 'type' => 'pint', 'msg' => '城市id格式不正确！'),
            array('key' => 'city_name', 'val' => $cityName, 'require' => false, 'type' => 'chinese', 'msg' => '城市名称不正确！')
        );
        if (!$cityId && !$cityName)
            $this->error('缺少参数');

        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.获取地区列表
        if ($cityId) {
            $result = $this->areaModel->getAreaByCityId($cityId);
        } elseif ($cityName) {
            $result = $this->areaModel->getAreaByCityName($cityName);
        }
        $this->output($result);
    }

    /**
     * @name 获取商区列表
     * @param $city_id
     */
    public function getBusinessDistrict() {
        //1.验证是否登陆
        //parent::auth();
        //2.接收参数并验证

        $cityId = getParameter('city_id');
        $cityName = getParameter('city_name');
        $params = array(
            array('key' => 'city_id', 'val' => $cityId, 'require' => false, 'type' => 'pint', 'msg' => '城市id格式不正确！'),
            array('key' => 'city_name', 'val' => $cityName, 'require' => false, 'type' => 'chinese', 'msg' => '城市名称不正确！')
        );
        if (!$cityId && !$cityName)
            $this->error('缺少参数');
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.获取商区列表
        if ($cityId) {
            $result = $this->areaModel->getBusinessDistrictByCityId($cityId);
        } elseif ($cityName) {
            $result = $this->areaModel->getBusinessDistrictByCityName($cityName);
        }
        if ($result) {
            $this->output($result);
        } else {
            $this->error('获取失败');
        }
    }

    /**
     * @name 获取喜欢的类型选项
     */
    public function getFavoriteOptions() {
        //1.验证是否登陆
        parent::auth();
        //2.获取分类
        $data = $this->categoryModel->getAll();
        foreach ($data AS $key => $val) {
            $data[$key]['items'] = $this->categoryLabelModel->getListByCategoryId($val['id']);
        }
        $this->output($data);
    }

    /**
     * 获取用户搜索记录
     */
    public function getSearchRecord() {
        $user_info = $this->getUserInfo();

        if (!$user_info)
            return $this->error('请先登录');
        $list = D('User')->getSearchRecord($user_info['user_id']);
        $this->output($list);
    }

    /**
     * @name 获取喜欢的商家选项
     */
    public function getFavoriteBusinessOptions() {
        //1.验证是否登陆
        parent::auth();
        //2.获取用户信息
        $userInfo = $this->getUserInfo();
        //3.获取数据
        $data = $this->shopsModel->getFavoriteBusinessOptions($userInfo['user_id']);
        $this->output($data);
    }

    /**
     * @name 保存选择的商区
     */
    public function saveBusinessDistrict() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $businessDistrictIds = getParameter('business_district_ids');
        $params = array(
            array('key' => 'business_district_ids', 'val' => $businessDistrictIds, 'require' => true, 'msg' => '请选择商区！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        $businessDistricts = explode('-', $businessDistrictIds);
        if (count($businessDistricts) > 3)
            $this->error('最多只能选择三个商区');
        foreach ($businessDistricts as $key => $val) {
            if (is_numeric($val) == false) {
                $this->error('参数错误');
            }
        }
        //3.保存商区
        $userInfo = $this->getUserInfo();
        $this->userBusinessDistrictModel->saveBusinessDistrict($userInfo['user_id'], $businessDistricts);
        $this->success('保存成功！');
    }

    /**
     * @name 保存用户选择的栏目
     */
    public function saveCategory() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $categoryIds = getParameter('category_ids');
        $params = array(
            array('key' => 'category_ids', 'val' => $categoryIds, 'require' => true, 'msg' => '请选择你喜欢的类型！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        $category = explode('-', $categoryIds);
        foreach ($category as $key => $val) {
            if (is_numeric($val) == false) {
                $this->error('参数错误');
            }
        }
        //3.保存栏目
        $userInfo = $this->getUserInfo();
        $this->userCategoryModel->savaCategory($userInfo['user_id'], $category);
        $this->success('保存成功！');
    }

    /**
     * @name 保存喜欢的商家
     */
    public function saveFavoriteBusiness() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $shopIds = getParameter('shop_ids');
        $params = array(
            array('key' => 'shop_ids', 'val' => $shopIds, 'require' => true, 'msg' => '请选择你喜欢的商家！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        $shop = explode('-', $shopIds);
        foreach ($shop as $key => $val) {
            if (is_numeric($val) == false) {
                $this->error('参数错误');
            }
        }
        //3.保存
        $userInfo = $this->getUserInfo();
        $this->userLikeShopModel->saveFavoriteBusiness($userInfo['user_id'], $shop);
        $this->success('保存成功！');
    }

    public function tests() {
        pushMsg('你的注册验证码是123456', '18008000946');
    }

}
